﻿using Microsoft.Win32;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Model.DbContext.Biz;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Helper;
using System.Collections.ObjectModel;
using System.DirectoryServices.ActiveDirectory;
using System.IO;
using System.Windows;
using System.Windows.Input;

namespace SmartPlant.Modules.Base.ViewModels
{
    public class BatchTemplateSettingNewViewModel : DialogViewModelBase, IDialogAware
    {
        private int _templateType = 0;
        private DelegateCommand<object> _okDialogCommand;
        private DelegateCommand _uploadFilesCommand;
        private DelegateCommand _addFileCommand;
        private DelegateCommand _deleteFileCommand;

        private ITemplateSettingService _templateSettingService;


        public BatchTemplateSettingNewViewModel(ITemplateSettingService templateSettingService, IDialogService dialogService) : base(dialogService)
        {
            Title = "批量新建模板";

            _templateSettingService = templateSettingService;
        }

        public override void OnDialogOpened(IDialogParameters parameters)
        {
            TemplateFiles = new ObservableCollection<FileUploadModel>();


            base.OnDialogOpened(parameters);
        }


        private ObservableCollection<FileUploadModel> templateFiles;
        public ObservableCollection<FileUploadModel> TemplateFiles
        {
            get { return templateFiles; }
            set { SetProperty(ref templateFiles, value); }
        }

        private FileUploadModel selectedFile;
        /// <summary>
        /// 选中的
        /// </summary>
        public FileUploadModel SelectedFile
        {
            get { return selectedFile; }
            set { SetProperty(ref selectedFile, value); }
        }


        /// <summary>
        /// 批量上传模板
        /// </summary>
        public ICommand OkDialogCommand
        {
            get
            {
                if (_okDialogCommand != null) return _okDialogCommand;
                _okDialogCommand = new DelegateCommand<object>(onOkDialogCommand);
                return _okDialogCommand;
            }
        }


        public ICommand AddFileCommand
        {
            get
            {
                if (_addFileCommand != null) return _addFileCommand;
                _addFileCommand = new DelegateCommand(onAddFileCommand);
                return _addFileCommand;
            }
        }
        private void onAddFileCommand()
        {
            TemplateFiles.Add(new FileUploadModel());
        }

        public ICommand DeleteFileCommand
        {
            get
            {
                if (_deleteFileCommand != null) return _deleteFileCommand;
                _deleteFileCommand = new DelegateCommand(onDeleteFileCommand);
                return _deleteFileCommand;
            }
        }
        /// <summary>
        /// 删除模板上传窗口选中行
        /// </summary>
        private void onDeleteFileCommand()
        {
            TemplateFiles.Remove(selectedFile);
        }
        /// <summary>
        /// 批量上传模板
        /// </summary>
        /// <param name="parameter"></param>
        private async void onOkDialogCommand(object parameter)
        {
            if (templateFiles.Count < 1)
            {
                Dialog.ShowAltert("请先添加模版信息再点击上传！！！");
                return;
            }
            string proId = GlobalObject.CurrentProject.ProjId.ToString();

            #region 导入前数据检查
            for (int i = 0; i < templateFiles.Count(); i++)
            {
                var file = TemplateFiles[i];
                if (file.FileName == null)
                {
                    Dialog.ShowAltert(@$"第{i + 1}行的模版名称为空！！！");
                    //file.TemplateUploadInfo = "模版名称为空";
                    return;
                }
                //if (file.TemplatePath == null)
                //{
                //    Dialog.ShowAltert(@$"第{i + 1}行的模版路径为空！！！");
                //    //file.TemplateUploadInfo = "模版路径为空";
                //    return;
                //}
                if (file.TemplateType == null)
                {
                    Dialog.ShowAltert(@$"第{i + 1}行的模版类型为空！！！");
                    //file.TemplateUploadInfo = "模版类型为空";
                    return;
                }
                if (file.InputOutputType == null)
                {
                    Dialog.ShowAltert(@$"第{i + 1}行的输入输出为空！！！");
                    //file.TemplateUploadInfo = "输入输出为空";
                    return;
                }
                if (file.ExcelFilePath == null)
                {
                    Dialog.ShowAltert(@$"第{i + 1}行的Excel文件为空！！！");
                    //file.TemplateUploadInfo = "Excel文件为空";
                    return;
                }
                if (file.XmlFilePath == null)
                {
                    Dialog.ShowAltert(@$"第{i + 1}行的XML文件为空！！！");
                    //file.TemplateUploadInfo = "XML文件为空";
                    return;
                }
            }
            #endregion


            foreach (var file in templateFiles)
            {


                try
                {
                    int selectedIOType = 0;
                    if (file.InputOutputType == "输出")
                        selectedIOType = 1;
                    int selectedTemplateType = Convert.ToInt32(file.TemplateType);
                    Report report = new Report
                    {
                        Description = "",
                        GenerateFunc = "",
                        Name = file.FileName,
                        SQL = "",
                        TemplatePath = GlobalObject.CurrentProject.ProjName,
                        Type = (TemplateType)selectedTemplateType,
                        Parameters = "",
                        InOrOut = selectedIOType
                    };
                    var r = await _templateSettingService.CreateTemplateAsync(proId, report);

                    if (r.succeeded == true)
                    {
                        string filePath = file.ExcelFilePath;
                        if (File.Exists(filePath))
                        {
                            if (filePath.Contains(".xls") && !filePath.Contains(".xlsx"))
                            {
                                filePath = ExcelHelper.xls2xlsx(filePath.Replace(Path.GetFileName(filePath), ""), Path.GetFileName(filePath));
                            }
                            using var fileStream = new FileStream(filePath, FileMode.Open);
                            string fileNameExtension = Path.GetExtension(filePath);
                            await _templateSettingService.UploadTemplateFileAsync(proId, report.Type, fileStream, file.FileName + fileNameExtension, selectedIOType);
                        }
                        filePath = file.XmlFilePath;
                        if (File.Exists(filePath))
                        {

                            using var fileStream = new FileStream(filePath, FileMode.Open);
                            string fileNameExtension = Path.GetExtension(filePath);
                            await _templateSettingService.UploadTemplateFileAsync(proId, report.Type, fileStream, file.FileName + fileNameExtension, selectedIOType);
                        }


                    }
                    else
                    {
                        Dialog.ShowAltert(r.errors);
                        RaiseRequestClose(new DialogResult(ButtonResult.None));
                    }
                }
                catch (Exception x)
                {
                    var xMessage = $"新建失败：{x.Message}！！！";
                    LoggerHelper.Current.Error(xMessage, x);
                    Dialog.ShowAltert(xMessage);
                }


            }

            Dialog.ShowAltert("新建完成！！！");

            RaiseRequestClose(new DialogResult(ButtonResult.OK));

        }


    }
    /// <summary>
    /// 批量文件上传类
    /// </summary>
    public class FileUploadModel : BindableBase
    {
        private string excelFilePath;
        private string xmlFilePath;

        public string FileName { get; set; }
        public string TemplateUploadFlag { get; set; }
        public string TemplateUploadInfo
        {
            get; set;
        }
        //public string TemplatePath { get; set; }
        //

        private string _TemplateType;
        public string TemplateType
        {
            get
            {
                return _TemplateType;


            }
            set
            {

                SetProperty(ref _TemplateType, value);

                if (_TemplateType == ((int)SmartPlant.Model.TemplateType.SPEC).ToString())
                {
                    InputOutputType = "N/A";//因为batch的xaml里就是N/A
                }
                else
                {

                }
            }
        }
        private string _InputOutputType;
        public string InputOutputType
        {
            get { return _InputOutputType; }
            set
            {
                SetProperty(ref _InputOutputType, value);
            }
        }


        public string ExcelFilePath
        {
            get { return excelFilePath; }
            set { SetProperty(ref excelFilePath, value); }
        }

        public string XmlFilePath
        {
            get { return xmlFilePath; }
            set { SetProperty(ref xmlFilePath, value); }
        }

        public ICommand BrowseExcelCommand { get; set; }
        public ICommand BrowseXmlCommand { get; set; }

        public FileUploadModel()
        {
            TemplateUploadFlag = "N";


            BrowseExcelCommand = new RelayCommand(obj => BrowseExcel());
            BrowseXmlCommand = new RelayCommand(obj => BrowseXml());
        }

        private void BrowseExcel()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";

            if (openFileDialog.ShowDialog() == true)
            {
                ExcelFilePath = openFileDialog.FileName;
            }
        }

        private void BrowseXml()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";

            if (openFileDialog.ShowDialog() == true)
            {
                XmlFilePath = openFileDialog.FileName;
            }
        }
    }

    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Func<object, bool> _canExecute;

        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
}
